import { DataTypes } from 'sequelize';
import { v4 as uuidv4 } from 'uuid';
import { sequelize } from '../config/database.js';

const Order = sequelize.define('Order', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  order_no: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '订单号'
  },
  status: {
    type: DataTypes.ENUM('pending', 'paid', 'cancelled', 'refunded'),
    allowNull: false,
    defaultValue: 'pending',
    comment: '订单状态：pending-待支付，paid-已支付，cancelled-已取消，refunded-已退款'
  },
  external_order_no: {
    type: DataTypes.STRING(100),
    allowNull: true,
    comment: '外部订单号（支付平台）'
  },
  quota_type: {
    type: DataTypes.ENUM('general', 'domain', 'expert'),
    allowNull: false,
    comment: '购买的额度类型'
  },
  target_id: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: '目标ID（领域ID或专家ID）'
  },
  purchase_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '购买次数'
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    comment: '支付金额'
  },
  payment_method: {
    type: DataTypes.ENUM('wechat', 'alipay'),
    allowNull: true,
    comment: '支付方式'
  },
  paid_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '支付时间'
  },
  expires_at: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '订单过期时间'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  tableName: 'orders',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      name: 'idx_orders_order_no',
      unique: true,
      fields: ['order_no'],
    },
    {
      name: 'idx_orders_user_id',
      fields: ['user_id'],
    },
    {
      name: 'idx_orders_status',
      fields: ['status'],
    },
    {
      name: 'idx_orders_external_order_no',
      fields: ['external_order_no'],
    },
    {
      name: 'idx_orders_created_at',
      fields: ['created_at'],
    },
  ],
  hooks: {
    beforeCreate: (order) => {
      if (!order.order_no) {
        order.order_no = generateOrderNo();
      }
      // 设置订单过期时间（30分钟）
      if (!order.expires_at) {
        order.expires_at = new Date(Date.now() + 30 * 60 * 1000);
      }
    }
  }
});

// 生成订单号
function generateOrderNo() {
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substring(2, 8).toUpperCase();
  return `BZ${timestamp}${random}`;
}

// 实例方法
Order.prototype.toJSON = function() {
  const values = { ...this.get() };
  return values;
};

Order.prototype.isPaid = function() {
  return this.status === 'paid';
};

Order.prototype.isExpired = function() {
  return this.expires_at && new Date() > this.expires_at;
};

Order.prototype.canPay = function() {
  return this.status === 'pending' && !this.isExpired();
};

Order.prototype.markAsPaid = async function(paymentData = {}) {
  this.status = 'paid';
  this.paid_at = new Date();
  if (paymentData.external_order_no) {
    this.external_order_no = paymentData.external_order_no;
  }
  if (paymentData.payment_method) {
    this.payment_method = paymentData.payment_method;
  }
  await this.save();
  return this;
};

// 类方法
Order.findByOrderNo = function(orderNo) {
  return this.findOne({ 
    where: { order_no: orderNo },
    include: [
      { association: 'user', attributes: ['id', 'phone'] },
      { association: 'domain', attributes: ['id', 'name'] },
      { association: 'expert', attributes: ['id', 'nickname'] }
    ]
  });
};

Order.getUserOrders = function(userId, options = {}) {
  const { page = 1, limit = 20, status } = options;
  const where = { user_id: userId };
  
  if (status) {
    where.status = status;
  }
  
  return this.findAndCountAll({
    where,
    include: [
      { association: 'domain', attributes: ['id', 'name'] },
      { association: 'expert', attributes: ['id', 'nickname'] }
    ],
    order: [['created_at', 'DESC']],
    limit,
    offset: (page - 1) * limit
  });
};

Order.createOrder = async function(orderData) {
  return await this.create(orderData);
};

// 订单统计
Order.getStatistics = async function() {
  // 总订单数
  const total = await this.count();
  // 各状态订单数
  const pending = await this.count({ where: { status: 'pending' } });
  const paid = await this.count({ where: { status: 'paid' } });
  const cancelled = await this.count({ where: { status: 'cancelled' } });
  // 总金额（仅统计已支付）
  let totalAmount = 0;
  try {
    const paidOrders = await this.findAll({ where: { status: 'paid' }, attributes: ['amount'] });
    totalAmount = paidOrders.reduce((sum, o) => sum + parseFloat(o.amount), 0);
  } catch (e) {
    totalAmount = 0;
  }
  return { total: total || 0, pending: pending || 0, paid: paid || 0, cancelled: cancelled || 0, totalAmount: totalAmount || 0 };
};

export default Order;
